/** @format */
import  fs from 'fs'
import  path from 'path'
import  childProcess from 'child_process'
import  { validProdVersion } from './utils.js'
const rootPath = process.env.INIT_CWD
function writeNextVersion(version, filePath) {
    const buffer = fs.readFileSync(filePath)
    const data = JSON.parse(buffer.toString())
    data.version = version
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2))
}

function generateChangeLog(version, isProdVersion) {
    if (isProdVersion) {
        // 生成正式版本日志
        childProcess.execSync('npx conventional-changelog -p zentao -i CHANGELOG.md -s -r 0')
    } else {
        childProcess.execSync('npx conventional-changelog -p zentao -i CHANGELOG-TEST.md -s -r 1')
    }
    // 提交git
    try {
        childProcess.execSync(
            `git add ${isProdVersion ? 'CHANGELOG.md' : ''} package.json public/pub/defConfig.json && git commit -m"docs: ${version}版本更新"`
        )
    } catch (e) {
        console.log('[generateChangeLog error]')
        console.log(e)
    }
}
function generateTag(version) {
    childProcess.execSync(`git tag v${version} `)
    childProcess.execSync(`git push origin v${version}`)
}

export default function genTag(nextVersion) {
    const isProdVersion = validProdVersion(nextVersion)
    nextVersion = nextVersion.replace(/\.0/g, '.')
    if (!rootPath) {
        console.error('未在package.json中执行此命令')
        process.exit(1)
    }
    if (!nextVersion) {
        console.error('未获取version信息')
        process.exit(1)
    }
    const packagePath = path.resolve(rootPath, 'package.json')
    writeNextVersion(`1.${nextVersion}`, packagePath)
    console.log(`package.json version ${nextVersion} 写入成功`)
    generateChangeLog(`1.${nextVersion}`, isProdVersion)
    try {
        if (isProdVersion) {
            generateTag(`1.${nextVersion}`)
        } else {
            childProcess.execSync('git push')
            // autoBuild()
        }
    } catch (e) {
        console.log('[generateTag error]')
        console.log(e)
        // console.log(e)
    }
}




// 文件名2408085.01

// package 1.2408085.1
